package com.xinzhidi.web.task;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.xinzhidi.common.core.domain.model.LoginUser;
import com.xinzhidi.common.utils.SecurityUtils;
import com.xinzhidi.framework.websocket.WebSocketUsers;
import com.xinzhidi.web.equipmentAlarm.domain.EquipmentAlarm;
import com.xinzhidi.web.equipmentAlarm.domain.dto.EquipmentAlarmListDto;
import com.xinzhidi.web.equipmentAlarm.domain.vo.EquipmentAlarmListVo;
import com.xinzhidi.web.equipmentAlarm.service.EquipmentAlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 消息推送定时任务
 *
 * @author cx
 */
@Component("messagePush")
public class MessagePushTask {

    @Autowired
    private EquipmentAlarmService equipmentAlarmService;

    public void ryNoParams() {
        this.messagePush();
    }

    /**
     * 消息推送
     **/
    private String messagePush() {

        Map<String, Session> users = WebSocketUsers.getUsers();
        System.out.println("检查是否有可推送的消息");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return null;
        }
        Long userId = loginUser.getUser().getUserId();
        //查询需要消息提醒的告警
        EquipmentAlarmListDto dto = new EquipmentAlarmListDto();
        dto.setHideOrPush(0);
        dto.setStatus("0");
        List<EquipmentAlarmListVo> equipmentAlarms = equipmentAlarmService.getSendAlarmList(dto);
        if (CollectionUtils.isEmpty(equipmentAlarms)) {
            return null;
        }

        //找出需要发送的数据
        //1:找出未发送信息的数据（需要立即发送）
        List<EquipmentAlarmListVo> noSendList = Lists.newArrayList();
        for (EquipmentAlarmListVo vo : equipmentAlarms) {
            if (vo.getLastSendTime() == null) {
                noSendList.add(vo);
                continue;
            }
            LocalDateTime lastSendTime = vo.getLastSendTime();
            long minutes = Duration.between(LocalDateTime.now(), lastSendTime).toMinutes();
            //如果相差的分钟数是设置间隔数的整数，则需要推送
            if (minutes % vo.getPushInterval() == 0) {
                noSendList.add(vo);
            }
        }

        if (noSendList.size() > 0) {
            UpdateWrapper<EquipmentAlarm> updateWrapper = new UpdateWrapper<>();
            JSONObject jsonObject;
            for (EquipmentAlarmListVo vo : noSendList) {
                updateWrapper = new UpdateWrapper<>();
                jsonObject = new JSONObject();
                jsonObject.put("type", 1);
                jsonObject.put("message", "设备【" + vo.getEquipmentName() + "】" + vo.getAlarmTypeName());
                WebSocketUsers.sendMessageToUserByUserId(userId + "", jsonObject.toString());
            }

            updateWrapper.set("last_send_time", LocalDateTime.now()).in("id", noSendList.stream().map(EquipmentAlarmListVo::getId).toArray());
            equipmentAlarmService.update(updateWrapper);
        }
        return null;
    }
}
